<?php defined('SYSPATH') or die('No direct access allowed.');

class OpenLogin_Sina extends OpenLogin
{
    private $_openid = '';
    public function get_login_url($type="TOURIST")
    {
        $params['client_id'] = $this->_app_key;
        $params['redirect_uri'] = $this->_callback_url."?type=".$type;
        $params['state'] = $this->state();
        $wbaurl = "https://api.weibo.com/oauth2/authorize";
        return $wbaurl . "?" . http_build_query($params);
    }

    public function get_access_token()
    {
        $token_url = "https://api.weibo.com/oauth2/access_token";
        $data['client_id']     = $this->_app_key;
        $data['client_secret'] = $this->_app_secret;
        $data['grant_type']    = 'authorization_code';
        $data['code']          = (empty($_REQUEST['code']) ? '' : $_REQUEST['code']);
        $data['redirect_uri']  = $this->_callback_url;
        
        $data = http_build_query($data);
        $html = Utility::post_data($token_url, $data, true);
        $info = json_decode($html, true);
        $this->_openid = Arr::get($info, 'uid');
        return Arr::get($info, 'access_token');
    }
    
    public function get_openid($access_token)
    {
        return $this->_openid;
    }

    public function get_user_info($openid, $access_token)
    {
        $wb_graph_url = "https://api.weibo.com/2/users/show.json?uid=" . $openid .
            "&access_token=" . $access_token;
        
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $wb_graph_url);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
        $wb_str = curl_exec($ch); 
        curl_close($ch);

//        $wb_str = file_get_contents($wb_graph_url);
        $user = json_decode($wb_str, true);
        if (empty($user)) return false;
        if (!empty($user['error'])) return false;
        $info['uid']     = $openid;
        $info['userToken']  = $access_token;
        $info['gender']     = $user['gender'] == 'm' ? '男' : '女';
        $info['nickname']   = $user['name'];
        $info['header_url'] = $user['profile_image_url'];
        return $info;
    }
}
